package com.hotel.tools;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Author Str
 * @Date 2021/10/26 19:18
 * @Description :
 */
@WebFilter(urlPatterns = {"/*"})
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //{1}这里对对象进行类型转化(否则有些方法不能使用)
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        //{2}先获取到 Session 对象。
        HttpSession session = req.getSession();
        if (session != null) {  //你可能已经登录, 再作进一步确认。
            //{3}再从会话域中取出 user 对象。
            Object user = session.getAttribute("user");
            if (user != null) {  //证明你已经登录。
                //{5}有登录直接放行。
                chain.doFilter(req, resp);
                //{6}记住 return
                return;
            }
        }
        if (uri.contains("/login.jsp")||uri.contains("/")) {
            chain.doFilter(req, resp);
            return;
        }

        //{4}没有登录你会来到这里
        //   将你导航至 login.jsp。
        String ctxPath = req.getContextPath();
        String err = URLEncoder.encode("你需要登录才能访问系统资源", "UTF-8");
        resp.sendRedirect(ctxPath + "/login.jsp?err=" + err);
    }

    @Override
    public void init(FilterConfig filterConfig)
            throws ServletException {
    }

    @Override
    public void destroy() {
    }

}